//
// Created by linciping on 2020/8/27.
//
#include "util.h"

char* jstringToChar(JNIEnv *env,jstring jstr){
    char* rtn = NULL;
    jclass clsString = env->FindClass("java/lang/String");
    jstring strEncode = env->NewStringUTF("UTF-8");
    jmethodID methodGetBytes = env->GetMethodID(clsString, "getBytes", "(Ljava/lang/String;)[B");
    jbyteArray strBytes = (jbyteArray) env->CallObjectMethod(jstr, methodGetBytes, strEncode);
    jsize strLength = env->GetArrayLength(strBytes);
    jbyte* ba = env->GetByteArrayElements(strBytes, JNI_FALSE);
    if (strLength > 0) {
        rtn = (char*) malloc(strLength + 1);
        memcpy(rtn, ba, strLength);
        rtn[strLength] = 0;
    }
    env->ReleaseByteArrayElements(strBytes, ba, 0);
    return rtn;
}